#!/bin/bash

set -e
shopt -s extglob

if [ "${ACTION}" == "clean" ]; then
	echo Remove "${OBJECT_FILE_DIR}"
	[ -n "${OBJECT_FILE_DIR}" -a -d "${OBJECT_FILE_DIR}" ] && rm -rf "${OBJECT_FILE_DIR}"
else
	# For cmake & yasm
	PATH=$PATH:/opt/homebrew/bin:/usr/local/bin

	echo Build in ${OBJECT_FILE_DIR}
	for ARCH in $ARCHS; do
		mkdir -p "${OBJECT_FILE_DIR}/${ARCH}"
		cd "${OBJECT_FILE_DIR}/${ARCH}"
		if [ -f CMakeCache.txt ]; then
			echo Skipping cmake
		else
			cmake "${SRCROOT}/${TARGET_NAME}" -DCMAKE_INSTALL_PREFIX="${BUILT_PRODUCTS_DIR}/${ARCH}" -DCMAKE_BUILD_TYPE=${CONFIGURATION} -DCMAKE_OSX_ARCHITECTURES=${ARCH} -DCONFIG_AV1_ENCODER=0 -DENABLE_DOCS=0 -DENABLE_EXAMPLES=0 -DENABLE_TOOLS=0 -DAOM_TARGET_CPU=${ARCH}
		fi
		make -j`sysctl -n hw.physicalcpu` install
	done

	# Combine into Universal
	echo Installing into ${BUILT_PRODUCTS_DIR}/universal
	mkdir -p "${BUILT_PRODUCTS_DIR}/universal/include"
	cp -pr "${BUILT_PRODUCTS_DIR}/${ARCHS/ */}/include/aom" "${BUILT_PRODUCTS_DIR}/universal/include/"
	mkdir -p "${CONFIGURATION_BUILD_DIR}/universal/lib"
	lipo -create "${BUILT_PRODUCTS_DIR}/"+(${ARCHS/ /|})"/lib/libaom.a" -output "${BUILT_PRODUCTS_DIR}/universal/lib/libaom.a"
fi
